# -*- coding: utf-8 -*-
"""
Created on Thu Nov 17 23:04:33 2016
csv格式股票历史涨跌幅数据处理

"""

import numpy as np
import pandas as pd
import random
import csv
import sys
import string

#reload(sys)
#sys.setdefaultencoding('utf-8')

'''
    - 加载csv格式数据
'''


def loadCSVfile1(datafile):
    filelist = []
    with open(datafile,encoding='utf-8') as file:
        lines = csv.reader(file)
        #print(lines)
        for oneline in lines:
            filelist.append(oneline)
    filelist = np.array(filelist)
    return filelist


# 数据处理
# 随机选取30个历史涨跌幅数据
# 构建自己的数据库

def dataProcess(dataArr, subLen):
    totLen, totWid = np.shape(data)
    #print
    #totLen, totWid
    lenArr = dataArr[totLen - 1, 2:totWid]
    columnCnt = 1
    dataOut = []
    #print(lenArr)
    for lenData in lenArr:
        columnCnt = columnCnt + 1

        _lenDataInt = int(eval(lenData))
        print(type(_lenDataInt))
        N60 = _lenDataInt / (2 * subLen)
        #print
        #N60
        if N60 > 0:
            randIndex = random.sample(range(totLen - _lenDataInt - 1, totLen - subLen), N60)
            for i in randIndex:
                dataOut.append(dataArr[i:(i + subLen), columnCnt])
    dataOut = np.array(dataOut)

    return dataOut


if __name__ == "__main__":
    datafile = "600519.csv"
    data = loadCSVfile1(datafile)
    df = pd.DataFrame(data)
    m, n = np.shape(data)
    dataOut = dataProcess(data, 30)
    m, n = np.shape(dataOut)
    # 保存处理结果
    """
    csvfile = file('csvtest.csv', 'wb')
    writer = csv.writer(csvfile)
    writer.writerows(dataOut)
    csvfile.close()"""